package com.sundhage.misc {
	import flash.display.*;
	import flash.events.*;
	

	public class JSMagnifier extends Sprite {
		private var magGFX:Sprite;
		private var magMask:Sprite;
		private var smallPic:Sprite;
		private var bigPic:Sprite;
		
		private var smallPicLayer:Sprite;
		private var magnifier:Sprite;			// ska flyttas
		private var magContent:Sprite;
		
		private var dragMode:Boolean = false;
		
		private var mXOffs:int;
		private var mYOffs:int;
		private var magXStart:int;
		private var magYStart:int;
		
		private var xRatio:Number;
		private var yRatio:Number;
		
		
		// calc positions på allt
		private function mMove(e:Event):void {
			magnifier.x = magXStart-(mXOffs-mouseX);
			magnifier.y = magYStart-(mYOffs-mouseY);
			fixBigPicPos();
			//trace("mousemove!");
			
		}
		private function fixBigPicPos():void {
			bigPic.x = magnifier.x/(-xRatio)-((magMask.width)*xRatio);
			bigPic.y = magnifier.y/(-yRatio)-((magMask.height)*yRatio);
		}		
		private function mDown(e:Event):void {
			mXOffs = mouseX;
			mYOffs = mouseY;
			magXStart = magnifier.x;
			magYStart = magnifier.y;
			addEventListener(MouseEvent.MOUSE_MOVE, mMove);
			dragMode = true;
			
		}
		
		private function mUp(e:Event):void {
			if (dragMode) {
				dragMode = false;
				removeEventListener(MouseEvent.MOUSE_MOVE, mMove);
			}
		}
		
		private function init(e:Event):void {
			smallPicLayer = new Sprite();
			smallPicLayer.addChild(smallPic);
			

			magnifier = new Sprite();
			magContent = new Sprite();
			magContent.addChild(bigPic);
			magContent.addChild(magMask);
			magContent.mask = magMask;
			magnifier.addChild(magGFX);
			magnifier.addChild(magContent);
			
			magnifier.buttonMode = true;
			magnifier.addEventListener(MouseEvent.MOUSE_DOWN, mDown);
//			magnifier.addEventListener(MouseEvent.MOUSE_UP, mUp);
			stage.addEventListener(MouseEvent.MOUSE_UP, mUp);			
			
			addChild(smallPicLayer);
			addChild(magnifier);
			fixBigPicPos();
			
		}
		public function JSMagnifier(smallPic:Sprite, bigPic:Sprite, magnifier:Sprite, magnifierMask:Sprite) {
			this.smallPic = smallPic;
			this.bigPic = bigPic;
			this.magGFX = magnifier;
			this.magMask = magnifierMask;
			xRatio = smallPic.width/bigPic.width;
			yRatio = smallPic.height/bigPic.height;
			addEventListener(Event.ADDED_TO_STAGE, init);
//			init();
		}
		
	}
}